﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LapvBussiness;
using log4net;
using LapvWebComponent;
using LapvBussiness.Common;

namespace LapvWeb.Download
{
    public partial class DownloadFile : System.Web.UI.Page
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(DownloadFile).Name);
        public string domainStyle = ConfigLapv.Instance.DomainStyle;
        public string domain = ConfigLapv.Instance.DomainAdmin;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["PreUrl"] == null) Session["PreUrl"] = null;// ConfigLapv.Instance.DomainEdu;

            if (Page.User.Identity.IsAuthenticated == true)
            {
                int userid = SessionLogin.GetUsserId();
                if (userid > 0)
                {
                    log.Info(Session["PreUrl"]);
                    string _url = Request.Url.ToString();
                    string key = _url.Substring(_url.IndexOf("&pr=") + 4);

                    string key1 = Utilities.GetMD5Hash(DateTime.Now.ToString("ddMMyyyyhhmm") + "passdownload");
                    string key2 = Utilities.GetMD5Hash(DateTime.Now.AddMinutes(-1).ToString("ddMMyyyyhhmm") + "passdownload");



                    int docid = 0;
                    if (Request.QueryString["docid"] != null)
                        int.TryParse(Request.QueryString["docid"].ToString(), out docid);


                    if (docid > 0 && (key == key1 || key == key2))
                    {

                        //byte[] content;
                        //HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                        //WebResponse response = request.GetResponse();

                        //Stream stream = response.GetResponseStream();

                        //using (BinaryReader br = new BinaryReader(stream))
                        //{
                        //    content = br.ReadBytes(500000);
                        //    br.Close();
                        //}
                        //response.Close();

                        //Response.ContentType = "application/octet-stream";
                        //Response.AddHeader("Content-Disposition", "attachment; filename=\"" + HttpUtility.UrlDecode(filename) + "\"");
                        try
                        {
                            using (lapvwebEntities db = new lapvwebEntities())
                            {
                            //    document doc = db.document.Include("document_cate").Where(en => en.id == docid).FirstOrDefault();
                            //    if (doc != null)
                            //    {
                            //        account acc = db.account.Include("account_service").Include("account_service.service").Where(en => en.userid == userid && en.block == false).FirstOrDefault();
                            //        if (acc != null)
                            //        {
                            //            account_service acs = new account_service();
                            //            if (doc.document_cate.status > 0 && doc.document_cate.status < 5)
                            //                acs = acc.account_service.Where(ec => ec.service.id == 18 && ec.expiredate >= DateTime.Now).FirstOrDefault();
                            //            else if (doc.document_cate.status >= 5)
                            //                acs = acc.account_service.Where(ec => ec.service.id == 19 && ec.expiredate >= DateTime.Now).FirstOrDefault();
                            //            if (acs != null)
                            //            {
                            //                doc.downloadcount += 1;
                            //                db.ApplyPropertyChanges(doc.EntityKey.EntitySetName, doc);
                            //                db.SaveChanges();


                            //                //Response.BinaryWrite(content);
                            //                //download thanh cong
                            //                string path = ConfigEdu.Instance.DocumentUpload + doc.url;
                            //                string filename = "";
                            //                int i = doc.url.LastIndexOf('\\');
                            //                if (i != -1)
                            //                {
                            //                    filename = doc.url.Substring(i + 1, doc.url.Length - i - 1);
                            //                }
                            //                log.Info(path);
                            //                ASPUPLOADLib.IUploadManager objUpload = new ASPUPLOADLib.UploadManager();
                            //                objUpload.CodePage = 65001;
                            //                objUpload.SendBinary(path, true, "application/octet-binary", Request["File"], filename.Replace(" ", "_"));
                            //            }
                            //            else
                            //            {
                            //                if (acc.cash >= doc.cost)
                            //                {
                            //                    cash_log cashlog = new cash_log();
                            //                    cashlog.userid = userid;
                            //                    cashlog.value = doc.cost;
                            //                    cashlog.datetime = DateTime.Now;
                            //                    cashlog.type = 5;//download tai lieu
                            //                    cashlog.content = "Download tài liệu";
                            //                    cashlog.ip = Request.UserHostName;
                            //                    db.AddTocash_log(cashlog);
                            //                    acc.cash = acc.cash - doc.cost;
                            //                    ////Log cash
                            //                    doc.downloadcount += 1;
                            //                    db.ApplyPropertyChanges(acc.EntityKey.EntitySetName, acc);
                            //                    db.SaveChanges();
                            //                    Session["Cash"] = acc.cash;//update session cash

                            //                    //Response.BinaryWrite(content);
                            //                    //download thanh cong
                            //                    string path = ConfigEdu.Instance.DocumentUpload + doc.url;
                            //                    string filename = "";
                            //                    int i = doc.url.LastIndexOf('\\');
                            //                    if (i != -1)
                            //                    {
                            //                        filename = doc.url.Substring(i + 1, doc.url.Length - i - 1);
                            //                    }
                            //                    log.Info(path);
                            //                    ASPUPLOADLib.IUploadManager objUpload = new ASPUPLOADLib.UploadManager();
                            //                    objUpload.CodePage = 65001;
                            //                    objUpload.SendBinary(path, true, "application/octet-binary", Request["File"], filename.Replace(" ", "_"));

                            //                }
                            //                else
                            //                {
                            //                    log.Info("PreUrl: " + Session["PreUrl"].ToString());
                            //                    Session["DocManError"] = "Số dư tài khoản của trò còn " + acc.cash + ". Không đủ để tải tài liệu về";
                            //                    if (Session["PreUrl"] != null)
                            //                        Response.Redirect(Session["PreUrl"].ToString(), false);
                            //                }
                            //            }
                            //        }
                            //    }
                             }


                        }
                        catch (Exception ex)
                        {
                            //download loi
                            // redirect to error opening file page
                            log.Error("Download file lỗi: " + ex.Message + ". Stacktrace: " + ex.StackTrace);
                            Session["DocManError"] = "Download file lỗi: " + ex.Message;
                            if (Session["PreUrl"] != null)
                                Response.Redirect(Session["PreUrl"].ToString());
                        }
                    }
                    else
                    {
                        Session["DocManError"] = "Thông tin tải về không hợp lệ";
                        if (Session["PreUrl"] != null)
                            Response.Redirect(Session["PreUrl"].ToString());
                    }
                }
                else
                {
                    Session["DocManError"] = "Trò chưa đăng nhập";
                    if (Session["PreUrl"] != null)
                        Response.Redirect(Session["PreUrl"].ToString());
                }
            }
            else
            {
                Session["DocManError"] = "Trò chưa đăng nhập";
                if (Session["PreUrl"] != null)
                    Response.Redirect(Session["PreUrl"].ToString());
            }
        }
    }
}